package DataCenter;

import java.util.*;

import DataBasic.MetaHost;
import DataCenter.HostCenter.Fields;

public class HostAccessor extends MetaHost {

	private static HostAccessor instance;
	
	private HostCenter hostCenter;
	
	private List<String> names;
	private List<String> ips;
	private List<String> states;
	private List<String> ports;
	private List<String> uses;
	
	public synchronized static HostAccessor sharedInstance() {
		if (instance == null)
			instance = new HostAccessor();
		
		return instance;
	}

	private HostAccessor() {
		super();
		hostCenter = HostCenter.sharedInstance();
	}
	
	/*
	 * get host info
	 */
	
	public List<String> getHostNames() {
		if (names == null)
			names = hostCenter.generateListValueOfField(Fields.NAMES);
		
		return names;
	}
	
	public List<String> getHostIps() {
		if (ips == null)
			ips = hostCenter.generateListValueOfField(Fields.IPS);
		
		return ips;
	}
	
	public List<String> getHostPorts() {
		if (ports == null)
			ports = hostCenter.generateListValueOfField(Fields.PORTS);
		
		return ports;
	}
	
	public List<String> getHostStates() {
		if (states == null)
			states = hostCenter.generateListValueOfField(Fields.STATES);
		
		return states;
	}

	public List<String> getHostUses() {
		if (uses == null)
			uses = hostCenter.generateListValueOfField(Fields.USES);
		
		return uses;
	}
	
	public String getTheIpOfHost(String hostName) {
		ips = getHostIps();
		int index = names.indexOf(hostName);
		return ips.get(index);
	}
	
	public String getThePortOfHost(String hostName) {
		ports = getHostPorts();
		int index = names.indexOf(hostName);
		return ports.get(index);
	}
	
	/*
	 * locate the specified host
	 */
	
	public boolean isTheHostOnline(String hostName) {
		states = getHostStates();
		
		int index = names.indexOf(hostName);
		String state = states.get(index);
		
		if (state.equals("On"))
			return true;
		else
			return false;
	}
	
	public String findTheOnlineHost() {
		for (String name : names) {
			if (isTheHostOnline(name) && isTheHostUnusing(name))
				return name;
		}
		
		return null;
	}
	
	public boolean isTheHostUnusing(String hostName) {
		uses = getHostUses();
		
		int index = names.indexOf(hostName);
		String use = uses.get(index);
		
		if (use.equals("Yes"))
			return false;
		else
			return true;
	}
	
	/*
	 * print data
	 */
	
	public void printOnlineHosts() {
		String printContent = "Online hosts: ";
		for (String host : names) {
			if (this.isTheHostOnline(host))
				printContent += host + " ";
		}
		
		System.out.println(printContent);
	}
	
}
